/* 
 * ----------------------
 * Includes
 * ----------------------
 */
 
 // Standard
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

// SDL
#include <SDL.h>
#include <SDL/SDL_ttf.h>

// GUI
#include "elder_gui.h"

// Context
#include "context.h"

/* 
 * ----------------------
 * Global variables
 * ----------------------
 */
 
// Screen surface
extern SDL_Surface *screen;

// Current context
extern context currentContext;

/* 
 * ----------------------
 * Functions
 * ----------------------
 */
 
// Event manager (main loop)
void eventManager(void)
{
	int done = 0;
	int move = 0;
	SDL_Event event;
	int cpt = 0;
	
	
	while(done == 0)
    {
        
        // Wait for SDL events
        while(SDL_PollEvent(&event))
        {           
            // Event type
            switch(event.type)
            {
            	// SDL quit
                case SDL_QUIT:
                	done = 1;
                break;
                
                // Key hitted	
                case SDL_KEYDOWN:
                	switch(event.key.keysym.sym)
                	{
                		case SDLK_ESCAPE:
                			done = 1;
                		break;
                			
                		default:                			
                		break;
                	}
                
                // Mouse button pushed	
                case SDL_MOUSEBUTTONDOWN: 
                    move = 1;
                    //cursorPos = event.motion.x;
                break; 

				// Mouse button released
                case SDL_MOUSEBUTTONUP:
                	move = 0;
                	printf("You hit %d:%d !\n",event.motion.x,event.motion.y);
                	
                	// Check if TUX is clicked
                	if(event.motion.x <= 25 && event.motion.y <= 30)
                	{
                		currentContext.run = currentContext.run?0:1;
                		drawBackground();
                	}
                	
                	// Backlight control
                	if(event.motion.x >= 26 && event.motion.x <= 32 && event.motion.y >= 226 && event.motion.y <= 256)
                		setBrightness(3.333* (256-event.motion.y));
                		
            	
                break;

				// Mouse is mooving
                /*case SDL_MOUSEMOTION:
                    if( move == 1 )
                    {
                        //cursorPos = event.motion.x;
                    }
                break;*/
            }
        }

		// Repaint every 40ms (25fps)
        SDL_Delay(40);
        cpt++;
        
        // Every second
        if(cpt >= 25)
        {
        	cpt=0;
	        // Run ?
	        if(currentContext.run)
	        {
	        	// Decrease time every 25 loop (1sec..!)
		        
		        if(currentContext.timeLeft>0)
		        	(currentContext.timeLeft)--;
		        else
		        	currentContext.run = 0;
	        }
	        	
        	drawBackground();	
	    }
            
        
        
    }
	
}